import random
import re

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import ccp_send_sms_code


class GetMobileCodeView(View):

    def get(self, request, mobile):

        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({'success': False, 'message': '手机号格式错误'}, status=400)

        conn = get_redis_connection('verify_code')
        send_flag = conn.get(f'send_flag_{mobile}')

        if send_flag:
            return JsonResponse({'success': False, 'message': '发送短信过于频繁'}, status=400)

        sms_code = '%06d' % random.randint(0, 999999)

        ccp_send_sms_code.delay(mobile, sms_code)

        p = conn.pipeline()

        p.setex(f'sms_{mobile}', 300, sms_code)
        p.setex(f'send_flag_{mobile}', 60, 1)

        p.execute()

        return JsonResponse({'success': True, 'message': 'ok', 'sms_code': sms_code})





